import React, { useState,useEffect } from 'react';
import { Table,Modal,message,Button  } from 'antd';
import axios  from 'axios';
import servicePath from '../config/apiUrl';
import { useNavigate } from "react-router-dom";
const {confirm} = Modal 


function ArticleList(props){
    let navigate = useNavigate();
    const [list,setList] = useState()
    //只渲染一次 所以第二个参数为空数组
    useEffect(()=>{
        getList()
    },[])

    const getList = ()=>{
        axios({
            method:'get',
            url:servicePath.getArticleList,
            withCredentials:true,
        }).then(res=>{
            setList(res.data.data)
        })
    }
    //删除文章
    const delArticle =(data,index)=>{
        confirm({
            title:'确定要删除这篇文章吗？',
            content:'如果点击ok文章将永远删除，文章将永远被删除，无法恢复',
            onOk(){
                axios(servicePath.delArticle+'/' + data.id,{withCredentials:true}).then(res=>{
                    if (res.data.status) {
                        message.success('文章删除成功')
                        //不能再原数组中改变，这样会导致table不渲染， 如果不是这样，只会改变引用指向的内存数据，react 认为虚拟Dom没有改变
                        let newList = [...list]
                        newList.splice(index,1)
                        setList(newList)
                    }
                })
            },
            onCancel(){
                message.success('文章没有任何变化')
            }
        })
    }
    //修改文章的跳转方法
    const updataArticle =(data,checked)=>{
        navigate('/index/add/' + data.id)
    }

    //通过表格的方式渲染 数据
    //title 列
    let columns =[
        {title:'标题',dataIndex:'title',key:'title'},
        {title:'类别',dataIndex:'typeName',key:'typeName'},
        {title:'发布时间',dataIndex:'addTime',key:'addTime'},
        {title:'浏览量',dataIndex:'view_count',key:'view_count'},
        {title:'简介',dataIndex:'introduce',key:'introduce'},
        {title:'操作',dataIndex:'',key:'operate',render:(text,record,index)=>{
            return <div>
                        <Button type='primary' onClick={()=>{delArticle(text,index)}}>删除</Button> &nbsp;
                        <Button onClick={()=>{updataArticle(text)}}>修改</Button>
                    </div>
            
        }},
    ]
    return(
        <div>
          <Table columns={columns}
           dataSource={list}
           rowKey='id'
           expandable={{
            expandedRowRender: record => <p style={{ margin: 0 }}>{record.content}</p>,
            rowExpandable: record => record.content !== '放大',
          }}
          />
        </div>
    )
}

export default ArticleList